<script setup>
import { useUserStore } from '@/stores/userStore'
import { ref, reactive } from 'vue'
import { useUpdateUserAPI } from '@/apis/user'
import { useUpdateAvatarAPI } from '@/apis/user'
import { updatePasswordAPI } from '@/apis/user'
import { useAddressStore } from '@/stores/addressStore';
import { useInsertUserAddressAPI } from '@/apis/user';
import { useDeleteAddressAPI } from '@/apis/user'
import { useUpdateAddressAPI } from '@/apis/user'
import { useDefaultAddressAPI } from '@/apis/user'
import router from '@/router';
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
const addressStore = useAddressStore()
const uploadRef = ref()

// 定义响应式状态
const activeTab = ref('member') // 默认显示会员中心

const userStore = useUserStore()
const userInfo = ref({})
userInfo.value = userStore.userInfo.data.user


//弹窗控制
const dialog = ref(false)
const loading = ref(false)

//下面是用户信息的方法
const userForm = reactive({
    id: userInfo.value.id,
    password: userInfo.value.password,
    nickname: userInfo.value.nickname,
    gender: userInfo.value.gender,
    phone: userInfo.value.phone,
    email: userInfo.value.email
})

const userSubmit = async () => {
    loading.value = true
    const res = await useUpdateUserAPI(userForm)
    if (res.data.code === 0) loading.value = false
    setTimeout(() => {
        dialog.value = false
    }, 400)
    // 重新获取用户数据
    userStore.getNewUserInfo()
}

const handleClose = (done) => {
    if (loading.value) {
        return
    }
    ElMessageBox.confirm('你想要提交数据吗?', '误触了吗？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
    })
        .then(async () => {
            loading.value = true
            const res = await useUpdateUserAPI(userForm)
            if (res.data.code === 0) loading.value = false
            userStore.getNewUserInfo()
            timer = setTimeout(() => {
                done()
                // 动画关闭需要一定的时间
                setTimeout(() => {
                    loading.value = false
                }, 400)
            }, 2000)
        })
        .catch(() => {
            // catch error
        })

}

const cancelForm = () => {
    loading.value = false
    dialog.value = false
    clearTimeout(timer)
}

//用户头像地址
const imgUrl = ref(userStore.userInfo.data.user.userPic)

//下面是上传图片阿里云成功的回调函数
const uploadSuccess = (result) => {
    imgUrl.value = result.data;
}

//修改用户头像开始
const updateAvatar = async () => {
    let res = await useUpdateAvatarAPI(imgUrl.value)
    ElMessage.success(res.message ? res.message : '修改成功')
    userStore.getNewUserInfo()
}
//修改密码开始
const updatePasswordForm = reactive({
    old_pwd: '',
    new_pwd: '',
    re_pwd: '',
})

//校验密码的函数
const checkRePassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== updatePasswordForm.new_pwd) {
        callback(new Error('两次输入密码不一致'))
    } else {
        callback()
    }
}
//定义表单校验规则
const rules = {
    old_pwd: [
        { required: true, message: '原密码不能为空', trigger: 'blur' },
        { min: 5, max: 16, message: '请输入长度5~16的字符', trigger: 'blur' }
    ],
    new_pwd: [
        { required: true, message: '新密码不能为空', trigger: 'blur' },
        { min: 5, max: 16, message: '请输入长度5~16的字符', trigger: 'blur' }
    ],
    re_pwd: [
        //checkRePassword函数需要写道rules上面否则不能用
        { validator: checkRePassword, trigger: 'blur' }
    ]
}
//获取form实例做统一校验
const passwordForm = ref(null)

const updatePassword = async () => {
    //调用实例方法
    passwordForm.value.validate(async (valid) => {
        //valid:所以表单项都通过校验才为true
        if (valid) {
            let res = await updatePasswordAPI(updatePasswordForm)
            console.log("res");
            console.log(res);
            if (res.data.code === 0) {
                ElMessage.success(res.data.message ? res.data.message : '修改成功')
                updatePasswordForm.new_pwd = ''
                updatePasswordForm.old_pwd = ''
                updatePasswordForm.re_pwd = ''
                userStore.clearUserInfo()
                router.push('/login')
            } else {
                ElMessage.warning(res.data.message ? res.data.message : '修改失败')
            }
        }
    }
    )

}
//地址管理开始
const isAddAddress = ref(false)

const addressFrom = reactive({
    receiver: '',
    rePhone: '',
    fullLocation: '',
    detailedLocation: '',
    defaultAddress: '0'
})
//添加地址
const confirmAddressFrom = async () => {
    await useInsertUserAddressAPI(addressFrom)
    //重新获取用户地址
    addressStore.getAddressInfo()
    isAddAddress.value = false
    ElMessage.success("添加地址成功")
}
//删除地址
const deleteAddress = async (id) => {
    await useDeleteAddressAPI(id)
    ElMessage.success('删除地址成功')
    //重新获取用户地址
    addressStore.getAddressInfo()
}
//编辑地址
const isUpdate = ref(false)
const updateAddressFrom = ref({})
const getDetailAddress = (id) => {
    updateAddressFrom.value = addressStore.addressList.find(item => item.id === id);
    isUpdate.value = true
}
const confirmUpdateAddress = async () => {
    await useUpdateAddressAPI(updateAddressFrom.value)
    //重新获取用户地址
    addressStore.getAddressInfo()
    isUpdate.value = false
    ElMessage.success("修改地址成功")
}
//切换默认地址
const defaultAddress = async (id) => {
    await useDefaultAddressAPI(id)
    ElMessage.success('设置默认地址成功')
    //重新获取用户地址
    addressStore.getAddressInfo()
}
</script>

<template>
    <div class="home-overview">
        <!-- 用户信息 -->
        <div class="user-meta">
            <div class="avatar">
                <img :src="userStore.userInfo.data.user.userPic" />
            </div>
            <h4>{{ userStore.userInfo.data.user.nickname }}</h4>
        </div>
        <!-- 导航菜单 -->
        <div class="item">
            <a href="javascript:;" @click="activeTab = 'member'">
                <span class="iconfont icon-huiyuanzhongxin"></span>
                <p>会员中心</p>
            </a>
            <a href="javascript:;" @click="activeTab = 'avatar'">
                <span class="iconfont icon-SUI_xiugaitouxiang"></span>
                <p>更改头像</p>
            </a>
            <a href="javascript:;" @click="activeTab = 'password'">
                <span class="iconfont icon-xiugaimima"></span>
                <p>修改密码</p>
            </a>
            <a href="javascript:;" @click="activeTab = 'address'">
                <span class="iconfont icon-dizhiguanli"></span>
                <p>地址管理</p>
            </a>
        </div>
    </div>

    <!-- 内容区域 -->
    <div class="like-container">
        <!-- 会员中心 -->
        <div class="home-panel" v-show="activeTab === 'member'">
            <div class="header">
                <h4>个人资料</h4>
            </div>
            <div class="content">
                <!-- 会员中心内容 -->
                <el-form label-width="auto" style="max-width: 600px">
                    <el-form-item label="账户 :">
                        <el-input v-model="userStore.userInfo.data.user.username" disabled />
                    </el-form-item>
                    <el-form-item label="昵称 :">
                        <el-input v-model="userStore.userInfo.data.user.nickname" disabled />
                    </el-form-item>
                    <el-form-item label="性别 :">
                        <el-input v-model="userStore.userInfo.data.user.gender" disabled />
                    </el-form-item>
                    <el-form-item label="手机 :">
                        <el-input v-model="userStore.userInfo.data.user.phone" disabled />
                    </el-form-item>
                    <el-form-item label="邮箱 :">
                        <el-input v-model="userStore.userInfo.data.user.email" disabled />
                    </el-form-item>
                </el-form>
            </div>
            <div class="content">
                <el-button type="primary" @click="dialog = true">补充/修改</el-button>
            </div>
        </div>

        <!-- 更改头像 -->
        <div class="home-panel" v-show="activeTab === 'avatar'">
            <div class="header">
                <h4>更改头像</h4>
            </div>
            <!-- 头像上传组件 -->
            <el-upload ref="uploadRef" class="avatar-uploader" :show-file-list="false" :auto-upload="true"
                action="/api/upload" name="file" :headers="{ 'Authorization': userStore.userInfo.data.token }"
                :on-success="uploadSuccess">
                <img v-if="imgUrl" :src="imgUrl" class="avatar" />
                <img v-else :src="avatar" width="247" />
            </el-upload>
            <el-button type="primary" :icon="Plus" size="large" @click="uploadRef.$el.querySelector('input').click()">
                选择图片
            </el-button>
            <el-button type="success" :icon="Upload" size="large" @click="updateAvatar">
                上传头像
            </el-button>
        </div>

        <!-- 修改密码 -->
        <div class="home-panel" v-show="activeTab === 'password'">
            <div class="header">
                <h4>修改密码</h4>
            </div>
            <div class="content">
                <el-form label-width="auto" style="max-width: 600px" :model="updatePasswordForm" ref="passwordForm"
                    :rules="rules">
                    <el-form-item label="原密码 :" prop="old_pwd">
                        <el-input v-model="updatePasswordForm.old_pwd" type="password" :show-password="true" />
                    </el-form-item>
                    <el-form-item label="新密码 :" prop="new_pwd">
                        <el-input v-model="updatePasswordForm.new_pwd" type="password" :show-password="true" />
                    </el-form-item>
                    <el-form-item label="确认新密码 :" prop="re_pwd">
                        <el-input v-model="updatePasswordForm.re_pwd" type="password" :show-password="true" />
                    </el-form-item>
                </el-form>
                <div class="content">
                    <el-button type="primary" @click="updatePassword()">确认修改</el-button>
                </div>
            </div>
        </div>

        <!-- 地址管理 -->
        <div class="home-panel" v-show="activeTab === 'address'">
            <div class="header">
                <h4>地址管理</h4>
                <div class="extra">
                    <el-button type="primary" @click="isAddAddress = true">添加地址</el-button>
                </div>
            </div>
            <!-- 地址列表 -->
            <el-table :data="addressStore.addressList" style="width: 100%">
                <el-table-column label="序号" width="100" type="index"> </el-table-column>
                <el-table-column label="收货人" prop="receiver"></el-table-column>
                <el-table-column label="手机号" prop="rePhone"></el-table-column>
                <el-table-column label="地址" prop="fullLocation"></el-table-column>
                <el-table-column label="详细地址" prop="detailedLocation"></el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="{ row }">
                        <el-button v-if="row.defaultAddress === 0" class="iconfont icon-wujiaoxing1" circle plain type="info"
                            @click="defaultAddress(row.id)"></el-button>
                        <el-button v-else class="iconfont icon-wujiaoxing" circle plain type="success"></el-button>
                        <el-button :icon="Edit" circle plain type="primary"
                            @click="getDetailAddress(row.id)"></el-button>
                        <el-button :icon="Delete" circle plain type="danger" @click="deleteAddress(row.id)"></el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="没有数据" />
                </template>
            </el-table>
        </div>
    </div>
    <!-- 用户弹出页是这个 -->
    <el-drawer v-model="dialog" title="修改用户信息" :before-close="handleClose" direction="rtl" size="50%">
        <div>
            <el-form :model="userForm">
                <el-form-item label="昵称" :label-width="formLabelWidth">
                    <el-input v-model="userForm.nickname" autocomplete="off" />
                </el-form-item>
                <el-form-item label="性别">
                    <el-select v-model="userForm.gender" placeholder="请选择你的性别" clearable>
                        <!-- 使用 :value 绑定不同类型 -->
                        <el-option label="保密" :value="2" />
                        <el-option label="男" :value="1" />
                        <el-option label="女" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="手机" :label-width="formLabelWidth">
                    <el-input v-model="userForm.phone" autocomplete="off" />
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth">
                    <el-input v-model="userForm.email" autocomplete="off" />
                </el-form-item>
            </el-form>
            <div>
                <el-button @click="cancelForm">取消</el-button>
                <el-button type="primary" :loading="loading" @click="userSubmit">
                    {{ loading ? '提交中 ...' : '提交' }}
                </el-button>
            </div>
        </div>
    </el-drawer>
    <!-- 添加地址 -->
    <el-dialog v-model="isAddAddress" title="添加收货地址" width="30%" center>
        <div class="addressWrapper">
            <el-form :model="addressFrom" label-position="top">
                <el-form-item label="收货人">
                    <el-input v-model="addressFrom.receiver" />
                </el-form-item>
                <el-form-item label="收货手机号">
                    <el-input v-model="addressFrom.rePhone" />
                </el-form-item>
                <el-form-item label="所在地区">
                    <el-input v-model="addressFrom.fullLocation" />
                </el-form-item>
                <el-form-item label="详细地址与门牌号">
                    <el-input v-model="addressFrom.detailedLocation" />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="isAddAddress = false">取消</el-button>
                <el-button type="primary" @click="confirmAddressFrom">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 修改地址 -->
    <el-dialog v-model="isUpdate" title="修改收货地址" width="30%" center>
        <div class="addressWrapper">
            <el-form :model="updateAddressFrom" label-position="top">
                <el-form-item label="收货人">
                    <el-input v-model="updateAddressFrom.receiver" />
                </el-form-item>
                <el-form-item label="收货手机号">
                    <el-input v-model="updateAddressFrom.rePhone" />
                </el-form-item>
                <el-form-item label="所在地区">
                    <el-input v-model="updateAddressFrom.fullLocation" />
                </el-form-item>
                <el-form-item label="详细地址与门牌号">
                    <el-input v-model="updateAddressFrom.detailedLocation" />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="isUpdate = false">取消</el-button>
                <el-button type="primary" @click="confirmUpdateAddress">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped lang="scss">
.home-overview {
    height: 132px;
    background: url(@/assets/images/center-bg.png) no-repeat center / cover;
    display: flex;

    .user-meta {
        flex: 1;
        display: flex;
        align-items: center;

        .avatar {
            width: 85px;
            height: 85px;
            border-radius: 50%;
            overflow: hidden;
            margin-left: 60px;

            img {
                width: 100%;
                height: 100%;
            }
        }

        h4 {
            padding-left: 26px;
            font-size: 18px;
            font-weight: normal;
            color: white;
        }
    }

    .item {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-around;

        &:first-child {
            border-right: 1px solid #f4f4f4;
        }

        a {
            color: white;
            font-size: 16px;
            text-align: center;

            .iconfont {
                font-size: 32px;
            }

            p {
                line-height: 32px;
            }
        }
    }
}

.like-container {
    margin-top: 20px;
    border-radius: 4px;
    background-color: #fff;
}

.home-panel {
    background-color: #fff;
    padding: 0 20px;
    margin-top: 20px;
    height: 400px;

    .header {
        height: 66px;
        border-bottom: 1px solid #f5f5f5;
        padding: 18px 0;
        display: flex;
        justify-content: space-between;
        align-items: baseline;

        h4 {
            font-size: 22px;
            font-weight: 400;
        }

    }

    .avatar-uploader {
        :deep() {
            .avatar {
                width: 247px;
                height: 247px;
                display: block;
            }

            .el-upload {
                border: 1px dashed var(--el-border-color);
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                transition: var(--el-transition-duration-fast);
            }

            .el-upload:hover {
                border-color: var(--el-color-primary);
            }

            .el-icon.avatar-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                width: 278px;
                height: 278px;
                text-align: center;
            }
        }
    }
}
</style>